//
//  PayKeyBoardViewController.m
//  联付商圈
//
//  Created by apple on 17/7/20.
//  Copyright © 2017年 lianfu. All rights reserved.
//

#import "PayKeyBoardViewController.h"
#import "ReceiptViewController.h"
#import "PayViewController.h"
#import "KeyBoardCollectionViewCell.h"
#import "CommentaryPopView.h"
#import "BankCardViewController.h"

@interface PayKeyBoardViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, CommentaryPopViewDelegate>
@property (nonatomic, strong) UITextField *numTxtField;//具体金额
@property (nonatomic, strong) UILabel *currentRateLabel;//当前交易手续费
@property (nonatomic, strong) NSArray *itemArr;//键盘按钮数组
@property (nonatomic, copy) NSString *numString;
@end

@implementation PayKeyBoardViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.navigationController.navigationBar.hidden = YES;
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self addGesture];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    self.tabBarController.tabBar.hidden = NO;

}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self buildMainInterface];
}

- (void)addGesture {
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    SQUserModel *model = [SQUserModel yy_modelWithDictionary:dic];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    if (!dic || model.state.integerValue == 1) {
        [self.view addGestureRecognizer:tapGesture];
    } else {
        [self.view removeGestureRecognizer:tapGesture];
    }
}

- (void)buildMainInterface
{
//    UIButton *qrcodeBtn = [[UIButton alloc] init];
//    [qrcodeBtn setImage:[UIImage imageNamed:@"qrCode"] forState:UIControlStateNormal];
//    [qrcodeBtn addTarget:self action:@selector(qrcodeAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:qrcodeBtn];
//    [qrcodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view.mas_top).offset(40*FONTSIZE);
//        make.left.equalTo(self.view.mas_left).offset(30);
//        make.width.height.mas_equalTo(40);
//    }];
    
    //图标
    UIImageView *storeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"store"]];
    [self.view addSubview:storeImageView];
    [storeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(40 * FONTSIZE);
        make.left.equalTo(self.view.mas_left).offset((SCREENW - 30 * FONTSIZE) / 2);
        make.right.equalTo(self.view.mas_right).offset(-(SCREENW - 30 * FONTSIZE) / 2);
        make.height.mas_equalTo(30 * FONTSIZE);
    }];
    
    
    //标题
    UILabel *storeLabel = [[UILabel alloc] init];
    storeLabel.text = @"店铺收银台";
    storeLabel.textAlignment = 1;
    storeLabel.font = [UIFont systemFontOfSize:15 * FONTSIZE];
    [self.view addSubview:storeLabel];
    [storeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(storeImageView.mas_bottom).offset(10 * FONTSIZE);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.height.mas_equalTo(20 * FONTSIZE);
    }];
    
    //第一条分割线
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1.0];
    [self.view addSubview:lineView1];
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(storeLabel.mas_bottom).offset(20 * FONTSIZE);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.height.mas_equalTo(1);
    }];
    
    //第二条分割线
    UIView *lineView2 = [[UIView alloc] init];
    lineView2.backgroundColor = lineView1.backgroundColor;
    [self.view addSubview:lineView2];
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView1.mas_bottom).offset(100 * FONTSIZE);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.height.mas_equalTo(1);
    }];
    
    //金额(￥)
    UILabel *moneyLabel = [[UILabel alloc] init];
    moneyLabel.text = @"金额(￥)";
    moneyLabel.font = [UIFont systemFontOfSize:18 * FONTSIZE];
    [self.view addSubview:moneyLabel];
    [moneyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10 * FONTSIZE);
        make.bottom.equalTo(lineView2.mas_top).offset(-20 * FONTSIZE);
        make.width.mas_equalTo(100 * FONTSIZE);
        make.height.mas_equalTo(30 * FONTSIZE);
    }];
    
    //具体金额
    self.numTxtField = [[UITextField alloc] init];
    self.numTxtField.textColor = [UIColor colorWithRed:0.78 green:0.77 blue:0.80 alpha:1.00];
    self.numTxtField.font = [UIFont systemFontOfSize:40 * FONTSIZE];
    self.numTxtField.textAlignment = 2;
    self.numTxtField.placeholder = @"0.0";
    [self.numTxtField setEnabled:NO];
    [self.view addSubview:_numTxtField];
    [self.numTxtField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view.mas_right).offset(-20 * FONTSIZE);
        make.bottom.equalTo(lineView2.mas_top).offset(-20 * FONTSIZE);
        make.left.equalTo(moneyLabel.mas_right).offset(0);
        make.height.mas_equalTo(40 * FONTSIZE);
    }];
    
    //第三条分割线
    UIView *lineView3 = [[UIView alloc] init];
    lineView3.backgroundColor = lineView1.backgroundColor;
    [self.view addSubview:lineView3];
    [lineView3 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(-124 * FONTSIZE);
        make.height.mas_equalTo(1);
    }];
    
    //收款按钮
    UIButton *receiptButton = [UIButton buttonWithType:UIButtonTypeCustom];
    receiptButton.backgroundColor = [UIColor colorWithRed:0.00 green:0.61 blue:0.89 alpha:1.00];
    [receiptButton setTitle:@"收   款" forState:UIControlStateNormal];
    [receiptButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [receiptButton addTarget:self action:@selector(shopCashier) forControlEvents:UIControlEventTouchUpInside];
    receiptButton.layer.cornerRadius = 25 * FONTSIZE;
    [self.view addSubview:receiptButton];
    CGFloat contentHeight = (74 * FONTSIZE - 49) / 2;
    [receiptButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(30 * FONTSIZE);
        make.right.equalTo(self.view.mas_right).offset(-30 * FONTSIZE);
        make.top.equalTo(lineView3.mas_bottom).offset(contentHeight);
        make.height.mas_equalTo(50 * FONTSIZE);
    }];
    
    //键盘部分
    //交易费率
    self.currentRateLabel = [self makeLabelWithText:@"当前交易手续费:0.6%" Font:[UIFont systemFontOfSize:17 * FONTSIZE] TextColor:[UIColor colorWithRed:0.45 green:0.44 blue:0.47 alpha:1.00] TextAlignment:0];
    [self.view addSubview:_currentRateLabel];
    [self.currentRateLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(10 * FONTSIZE);
        make.top.equalTo(lineView2.mas_bottom).offset(10 * FONTSIZE);
        make.width.mas_equalTo(200 * FONTSIZE);
        make.height.mas_equalTo(20 * FONTSIZE);
    }];
    
    //点此降低
//    UIButton *reduceButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [reduceButton setTitle:@"点此降低" forState:UIControlStateNormal];
//    [reduceButton setTitleColor:[UIColor colorWithRed:0.89 green:0.09 blue:0.10 alpha:1.00] forState:UIControlStateNormal];
//    reduceButton.titleLabel.font = [UIFont systemFontOfSize:17 * FONTSIZE];
//    [reduceButton addTarget:self action:@selector(lowerTheRate) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:reduceButton];
//    CGFloat width = [self calculateRowWidth:reduceButton.titleLabel.text FontSize:18 Height:20];
//    [reduceButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.equalTo(self.view.mas_right).offset(-20 * FONTSIZE);
//        make.top.equalTo(lineView2.mas_bottom).offset(10* FONTSIZE);
//        make.width.mas_equalTo(width);
//        make.height.mas_equalTo(20 * FONTSIZE);
//    }];
    
    //键盘
    UIView *keyBoardView = [[UIView alloc] init];
    keyBoardView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:keyBoardView];
    [keyBoardView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.bottom.equalTo(lineView3.mas_top).offset(0);
        make.top.equalTo(self.currentRateLabel.mas_bottom).offset(5 * FONTSIZE);
    }];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.itemSize = CGSizeMake(SCREENW / 4, SCREENW / 4);
    
    UICollectionView *keyBoardCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREENW, SCREENW / 4 * 3) collectionViewLayout:layout];
    keyBoardCollectionView.backgroundColor = [UIColor whiteColor];
    keyBoardCollectionView.delegate = self;
    keyBoardCollectionView.dataSource = self;
    [keyBoardView addSubview:keyBoardCollectionView];
    [keyBoardCollectionView registerClass:[KeyBoardCollectionViewCell class] forCellWithReuseIdentifier:@"keyBoardCell"];
    
    self.itemArr = @[@"1", @"2", @"3", @"删除", @"4", @"5", @"6", @".", @"7", @"8", @"9", @"0"];
    _numString = [NSString string];
}

-(void)textFieldEditChanged:(UITextField *)textField
{
    if (textField.text.length >= 9) {
        _numTxtField.text = [textField.text substringToIndex:9];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _itemArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    KeyBoardCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"keyBoardCell" forIndexPath:indexPath];
    cell.numLabel.text = [_itemArr objectAtIndex:indexPath.row];
    if (indexPath.row == 3) {
        cell.numLabel.font = [UIFont systemFontOfSize:20 * FONTSIZE];
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != 7) {
        if ([_numTxtField.text isEqualToString:@"0"]) {
            _numTxtField.text = @"";
        }
        if (indexPath.row == 11) {
            _numTxtField.text = [_numTxtField.text stringByAppendingString:@"0"];
        } else {
            if (indexPath.row != 3) {
                _numTxtField.text = [_numTxtField.text stringByAppendingString:[NSString stringWithFormat:@"%@", [_itemArr objectAtIndex:indexPath.row]]];
                if ([_numTxtField.text containsString:@"."] && _numTxtField.text.length >= [_numTxtField.text rangeOfString:@"."].location + 4) {
                        _numTxtField.text = [_numTxtField.text substringToIndex:[_numTxtField.text rangeOfString:@"."].location + 3];
                }
            } else {
                if (_numTxtField.text.length > 0) {
                    _numTxtField.text = [_numTxtField.text substringToIndex:_numTxtField.text.length - 1];
                }
            }
        }
    } else {
        NSRange range = [_numTxtField.text rangeOfString:@"."];
        if (range.location == NSNotFound) {
            _numTxtField.text = [_numTxtField.text stringByAppendingString:@"."];
            if ([[_numTxtField.text substringToIndex:1] isEqualToString:@"."]) {
                NSMutableString *str = [[NSMutableString alloc] initWithString:_numTxtField.text];
                [str insertString:@"0" atIndex:0];
                _numTxtField.text = [NSString stringWithFormat:@"%@", str];
            }
        }
    }
    [self textFieldEditChanged:_numTxtField];
}

- (void)shopCashier
{
    if (![self.numTxtField.text isEqualToString:@""]) {
        NSArray *arr = @[/*@"收款码支付",*/ @"支付宝"];
        CommentaryPopView *commentView = [CommentaryPopView sheetWithTitle:@"请选择付款方式" buttonTitles:arr delegate:self];
        [commentView show];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"请输入金额" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:0 handler:nil];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)lowerTheRate
{
    PayViewController *payVC = [[PayViewController alloc] init];
    payVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:payVC animated:YES];
}

- (void)actionSheet:(CommentaryPopView *)actionSheet didClickedButtonAtIndex:(NSInteger)buttonIndex {
//    if (buttonIndex == 0) {
//        ReceiptViewController *receiptVC = [[ReceiptViewController alloc] init];
//        receiptVC.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:receiptVC animated:YES];
//    } else
    if (buttonIndex == 0) {
        BankCardViewController *bankVC = [BankCardViewController new];
        bankVC.payAccount = self.numTxtField.text;
        bankVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:bankVC animated:YES];
        
    }
}

- (void)qrcodeAction {
    ReceiptViewController *receiptVC = [[ReceiptViewController alloc] init];
    receiptVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:receiptVC animated:YES];
}

- (void)tapAction {
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    SQUserModel *model = [SQUserModel yy_modelWithDictionary:dic];
    if (!dic) {
        [self addAlertControllerWithMessage:@"请登录" viewController:self];
    } else if((model.state.integerValue==1)&&dic){
        [self addAlertControllerWithMessage:@"请入驻商家" viewController:self];
    }
}

- (void)addAlertControllerWithMessage:(NSString *)message viewController:(UIViewController *)vc {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:okAction];
    [vc presentViewController:alertVC animated:YES completion:nil];
}

@end
